package remote

import (
	"common/logs"
	"connector/game"
	"errors"
	"github.com/nats-io/nats.go"
)

type NatsClient struct {
	serverId string
	conn     *nats.Conn
	readChan chan []byte
}

// Run 启动 nats 服务
func (n *NatsClient) Run() (err error) {
	n.conn, err = nats.Connect(game.Conf.ServersConf.Nats.Url)
	if err != nil {
		logs.Error("nats 服务连接异常：%v", err)
		return
	}
	go n.subscribe()
	return nil
}

// SendMsg 发送消息
func (n *NatsClient) SendMsg(dst string, msg []byte) error {
	if n.conn != nil {
		if err := n.conn.Publish(dst, msg); err != nil {
			return err
		}
		return nil
	}
	return errors.New("nats 服务未开启。")
}

func (n *NatsClient) Close() {
	if n.conn != nil {
		n.conn.Close()
	}
}

// 订阅消息
func (n *NatsClient) subscribe() {
	_, err := n.conn.Subscribe(n.serverId, func(msg *nats.Msg) {
		// 收到 nats client 发送的消息
		n.readChan <- msg.Data
	})
	if err != nil {
		logs.Error("nats 订阅消息异常：%v", err)
	}
}

func NewNatsClient(serverId string, readChan chan []byte) *NatsClient {
	return &NatsClient{
		serverId: serverId,
		readChan: readChan,
	}
}
